package com.project.erp.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.project.erp.common.dao.PropertyFilter;
import com.project.erp.common.utils.Page;
import com.project.erp.dao.system.UserDao;
import com.project.erp.model.system.Role;
import com.project.erp.model.system.User;
import com.project.erp.service.system.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService{

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private UserDao userDao;
	
	//出现Exception异常也回滚事务
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void saveUser(User user) {
		if(user.getCreateTime() == null){
			user.setCreateTime(new Date());
		}
		userDao.save(user);
	}
	
	//只读事务，可以提高效率
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public String getStatusById(Long id){
		return userDao.getStatusById(id);
	}

	@Override
	public Page<User> getUserByPage(Page<User> page,List<PropertyFilter> propertyFilters) {
		return userDao.getUserByPage(page,propertyFilters);
	}

	@Override
	public Page<User> getUserPageBySearch(Page<User> page, User user) {
		return userDao.getUserPageBySearch(page, user);
	}
	
	@Override
	public User getUserById(Long userId){
		return userDao.get(userId);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void editUser(User user){
		userDao.save(user);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void delUser(String[] userIds){
		if(null == userIds || userIds.length == 0){
			return;
		}
		List<Long> ids = new ArrayList<Long>();
		for (String userId : userIds) {
			ids.add(Long.valueOf(userId));
		}
		//删除用户角色关联数据
		userDao.deleteUserRoleByuserIds(ids);
		//删除用户信息
		userDao.delUser(ids);
	}
	
	//只读事务，可以提高效率
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public User getUserByUserName(String loginName) {
		User user = userDao.queryUserByLoginName(loginName);
		//获取角色信息
		if(null != user){
			List<Role> roles = user.getRoleList();
			for (Role role : roles) {
				role.setPrivileges(null);
			}
		}
		return user;
	}
}
